﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Imports System.IO
Imports System.IO.Path
Imports Aspose
Imports Aspose.Words
Imports System.Net

Partial Class Control_MSDS_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJqueryMSDS()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJqueryMSDS()", "});"), True)
            End If
            BindStatus()
            BindToGrid()
            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
            hidIsUser.Value = Session("IsUser")
        End If
    End Sub
    Protected Sub BindStatus()
        Using data As New VSEntities
            Dim p = (From q In data.Status Select q).ToList
            ddlStatusId.AppendDataBoundItems = True
            ddlStatusId.Items.Add(New ListItem("---Tất cả---", -1))
            ddlStatusId.DataValueField = "StatusId"
            ddlStatusId.DataTextField = "Title"
            ddlStatusId.DataSource = p
            ddlStatusId.DataBind()
            ddlStatusId.SelectedValue = -1
            Dim lstFieldSort As String() = {"--- Chọn ---", "ItemName", "ItemCode", "VendorCode", "VendorName", "Created", "Creator", "Status"}
            With ddlFieldSort
                .DataSource = lstFieldSort
                .DataBind()
            End With
            ddlFieldSort.SelectedValue = "--- Chọn ---"
        End Using

    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1 _
           , Optional ByVal strItemCode As String = "" _
           , Optional ByVal strItemName As String = "" _
           , Optional ByVal strVendorCode As String = "" _
           , Optional ByVal strVendorname As String = "" _
           , Optional ByVal dtmCreatedFrom As Date = #1/1/1900# _
           , Optional ByVal dtmCreatedTo As Date = #12/31/3999# _
      )
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, strItemCode.ToString, strItemName.ToString, strVendorCode.ToString, strVendorname.ToString, dtmCreatedFrom.ToString, dtmCreatedTo.ToString}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue

            Dim p = data.uspMsdsoriginalSelectAll(strItemCode _
                , strItemName _
                , strVendorCode _
                , strVendorname _
                , dtmCreatedFrom _
                , dtmCreatedTo, ddlStatusId.SelectedValue _
                , ddlFieldSort.SelectedValue, txtCAS.Text _
               , iPage, intPag_Size).ToList

            If ddlFieldSort.SelectedValue = "--- Chọn ---" Then
                p = (From a In data.uspMsdsoriginalSelectAll(strItemCode _
                , strItemName _
                , strVendorCode _
                , strVendorname _
                , dtmCreatedFrom _
                , dtmCreatedTo, ddlStatusId.SelectedValue _
                , ddlFieldSort.SelectedValue, txtCAS.Text _
               , iPage, intPag_Size) Order By a.Id Descending Select a).ToList
            End If

            Dim strKey_Name() As String = {"Id", "ItemName", "StatusId", "OriginalFile", "StatusName"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.Count
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If
            Dim k = p.Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = k
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip) _
           , arrSearch(1).ToString _
           , arrSearch(2).ToString _
           , arrSearch(3).ToString _
           , arrSearch(4).ToString _
           , arrSearch(5) _
           , arrSearch(6) _
         )
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("Id").ToString
            Dim q = (From p In data.MSDSOriginals Where p.Id = intId Select p).FirstOrDefault
            Try
                data.MSDSOriginals.DeleteObject(q)
                data.SaveChanges()
                Insert_App_Log("Delete  Msdsoriginal:" & q.ItemCode & "--" & q.VendorCode & "", Function_Name.MSDSOriginal, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1 _
                 , arrSearch(1).ToString _
                 , arrSearch(2).ToString _
                 , arrSearch(3).ToString _
                 , arrSearch(4).ToString _
                 , arrSearch(5) _
                 , arrSearch(6) _
         )
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim q = (From p In data.MSDSOriginals Where p.Id = intId Select p).FirstOrDefault
                        Try
                            data.MSDSOriginals.DeleteObject(q)
                            Insert_App_Log("Delete  Msdsoriginal:" & q.ItemCode & "--" & q.VendorCode & "", Function_Name.MSDSOriginal, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            data.SaveChanges()
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        Dim arrSearch = ViewState("search")
        BindToGrid(1 _
           , arrSearch(1).ToString _
           , arrSearch(2).ToString _
           , arrSearch(3).ToString _
           , arrSearch(4).ToString _
           , arrSearch(5) _
           , arrSearch(6) _
         )
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowType = DataControlRowType.Header Then
            If Session("IsUser") <> 1 Then
                e.Row.Cells(10).Visible = False
            End If
        End If

        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1


            If Session("IsUser") <> 1 Then
                e.Row.Cells(10).Visible = False
            End If

            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            'lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")

            Dim lnkbtnvn As LinkButton = CType(e.Row.FindControl("lnkbtnvn"), LinkButton)


            Dim lnkbtnen As LinkButton = CType(e.Row.FindControl("lnkbtnen"), LinkButton)
            lnkbtnen.Attributes.Add("onclick", "return SetValue(" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & ");")

            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = "../../Page/MSDS/Edit.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString

            Dim hplItemName As HyperLink = CType(e.Row.FindControl("hplItemName"), HyperLink)
            hplItemName.NavigateUrl = "../../Page/MSDS/Detail.aspx?Id=" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
            hplItemName.Text = grdShow.DataKeys(e.Row.RowIndex)("ItemName").ToString
            'Permission edit
            Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
            If HasPermission(Function_Name.MSDSOriginal, Session("RoleID"), grdShow.DataKeys(e.Row.RowIndex)("StatusId").ToString, Audit_Type.Delete) = True Then
                lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Else
                lnkbtnDelete.Enabled = False
                chkItem.Enabled = False
            End If

            'permission edit
            If HasPermission(Function_Name.MSDSOriginal, Session("RoleID"), grdShow.DataKeys(e.Row.RowIndex)("StatusId").ToString, Audit_Type.Edit) = True Then
                hplEdit.Enabled = True
                lnkbtnvn.Enabled = True
                lnkbtnvn.Attributes.Add("onclick", "return SetValue(" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & ");")
            Else
                hplEdit.Enabled = False
                lnkbtnvn.Enabled = False
            End If

            'permission view
            If HasPermission(Function_Name.MSDSOriginal, Session("RoleID"), grdShow.DataKeys(e.Row.RowIndex)("StatusId").ToString, Audit_Type.ViewContent) = True Then
                hplItemName.Enabled = True

            Else
                hplItemName.Enabled = False
                hplItemName.NavigateUrl = "#"
            End If


            Dim lnkbtnViewvn As LinkButton = CType(e.Row.FindControl("lnkbtnViewvn"), LinkButton)
            If grdShow.DataKeys(e.Row.RowIndex)("StatusId") = 3 Then
                lnkbtnViewvn.Attributes.Add("onclick", "return SetValue(" & grdShow.DataKeys(e.Row.RowIndex)("Id").ToString & ");")
            Else
                lnkbtnViewvn.Enabled = False
            End If

            'check enable original
            Dim lnkbtnViewen As LinkButton = CType(e.Row.FindControl("lnkbtnViewen"), LinkButton)
            Dim DelPath = Server.MapPath("~/Uploads") & (grdShow.DataKeys(e.Row.RowIndex)("OriginalFile").ToString.Replace(MainDomain & "Uploads", ""))
            If (System.IO.File.Exists(DelPath)) Then
                lnkbtnViewen.Attributes.Add("onclick", "javascript: return SetDownFile('" & grdShow.DataKeys(e.Row.RowIndex)("OriginalFile").ToString & "');")
            Else
                lnkbtnViewen.Enabled = False
            End If


            'lnkbtnViewen.Attributes.Add("onclick", "return SetValue('" & grdShow.DataKeys(e.Row.RowIndex)("OriginalFile").ToString & "');")
            ' '  lnkbtnViewen.Attributes.Add("onclick", String.Formsssat("window.open('{0}','{1}'); return fale;", grdShow.DataKeys(e.Row.RowIndex)("OriginalFile").ToString, "_blank"))

            Dim lblStatus As Label = CType(e.Row.FindControl("lblStatus"), Label)
            lblStatus.Text = grdShow.DataKeys(e.Row.RowIndex)("StatusName").ToString
            If grdShow.DataKeys(e.Row.RowIndex)("StatusId") = 3 Then
                lblStatus.CssClass = "Published"
            End If

            Dim lblExpired As Label = CType(e.Row.FindControl("lblExpired"), Label)
            Using _data As New VSEntities
                Dim _MSDSId As Integer = grdShow.DataKeys(e.Row.RowIndex)("Id").ToString
                Dim _section16 = (From q In _data.MSDSSection16 Where q.MSDSId = _MSDSId Select q).FirstOrDefault
                If Not _section16 Is Nothing Then
                    If Not _section16.S1651 Is Nothing Then
                        lblExpired.Text = _section16.S1651
                    End If
                End If
            End Using

        End If

    End Sub
    Protected Sub lnkbtnVN_Click(ByVal sender As Object, ByVal e As EventArgs)
        Session("LanguageId") = 1
        Response.Redirect("Section01.aspx?Id=" & hidID.Value, False)
    End Sub
    Protected Sub lnkbtnEN_Click(ByVal sender As Object, ByVal e As EventArgs)
        Session("LanguageId") = 2
        Response.Redirect("Section01.aspx?Id=" & hidID.Value, False)
    End Sub
    Protected Sub lnkbtnViewVN_Click(ByVal sender As Object, ByVal e As EventArgs)
        Session("LanguageId") = 1
        ExportDoc()


        ' Response.Redirect("ExportDocument.aspx?Id=" & hidID.Value, False)
    End Sub
    'Protected Sub lnkbtnViewEN_Click(ByVal sender As Object, ByVal e As EventArgs)
    '	Session("LanguageId") = 2
    '	Response.Redirect("ViewMSDS.aspx?Id=" & hidID.Value, False)
    '	'Response.Redirect(hidID.Value, False)
    'End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1 _
          , txtItemcode.Text.Trim _
         , txtItemname.Text.Trim _
         , txtVendorcode.Text.Trim _
         , txtVendorname.Text.Trim _
         , StringToDate(txtCreatedFrom.Text.Trim, "dd/mm/yyyy") _
         , StringToDate(IIf(String.IsNullOrEmpty(txtCreatedTo.Text.Trim) = True, "31/12/3999", txtCreatedTo.Text.Trim), "dd/mm/yyyy") _
         )
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1).ToString _
           , arrSearch(2).ToString _
           , arrSearch(3).ToString _
           , arrSearch(4).ToString _
           , arrSearch(5) _
           , arrSearch(6) _
         )
    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click

        txtItemcode.Text = ""
        txtItemname.Text = ""
        txtVendorcode.Text = ""
        txtVendorname.Text = ""
        txtCreatedFrom.Text = ""
        txtCreatedTo.Text = ""
        txtCAS.Text = ""
        ddlFieldSort.SelectedIndex = -1
        drpPage_Size.SelectedIndex = -1
        BindToGrid(1)
    End Sub
#End Region
    Protected Sub ExportDoc()
        Dim FolderPath = Server.MapPath("~/Template").ToString
        Dim attributes As FileAttributes = File.GetAttributes(FolderPath & "\MSDS.docx")
        If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
            attributes = attributes And Not FileAttributes.ReadOnly
            File.SetAttributes(FolderPath & "\MSDS.docx", attributes)
        End If
        Dim LanguageId = Session("LanguageId").ToString()
        Dim FileName As String = ""
        Using document As Novacode.DocX = Novacode.DocX.Load(FolderPath & "\MSDS.docx")
            Using data As New VSEntities

                '************************* Section 1 *****************************
                Dim p1 = (From q In data.MSDSSection01 Where q.LanguageId = LanguageId And q.MSDSId = hidID.Value).FirstOrDefault()
                If p1 Is Nothing Then
                    Excute_Javascript("AlertboxRedirect('MSDS chưa nhập đầy đủ dữ liệu vui lòng kiểm tra lại','../../Page/MSDS/List.aspx');", Me.Page, True)
                    Exit Sub
                End If


                Dim p = (From q In data.MSDSOriginals Where q.Id = hidID.Value).FirstOrDefault

                'header
                document.ReplaceText("<<ItemCode>>", p.ItemCode)
                document.ReplaceText("<<ItemName>>", p.ItemName)
                document.ReplaceText("<<VendorCode>>", p.VendorCode)
                document.ReplaceText("<<VendorName>>", p.Vendorname)

                document.ReplaceText("<<date>>", Now.Date.ToString("dd/MM/yyyy"))

                document.ReplaceText("<<user name>>", Session("UserName"))


                document.ReplaceText("<<TenChat>>", If(IsNothing(p1.S101), "", p1.S101))
                document.ReplaceText("<<CASNo>>", p1.S104)
                document.ReplaceText("<<ECNo>>", p1.S105)
                document.ReplaceText("<<UNNo>>", p1.S106)


                ''TitlePage
                'document.ReplaceText("<<lblSection01Title>>", strlSection01Title)
                document.ReplaceText("<<S102>>", If(IsNothing(p1.S102), "", p1.S102))
                document.ReplaceText("<<S101>>", p1.S101)
                document.ReplaceText("<<S103>>", p1.S103)
                document.ReplaceText("<<S201>>", p1.S201 & " - " & p1.S203)
                document.ReplaceText("<<S301>>", p1.S301 & " - " & p1.S303)
                document.ReplaceText("<<S107>>", p1.S107)
                document.ReplaceText("<<S307>>", p1.S307)
                document.ReplaceText("<<S108>>", p1.S108)

                '************************* End Section 1 *****************************



                '************************* Section 3*****************************
                Dim p3 = (From q In data.MSDSSection03 Where q.LanguageId = LanguageId And q.MSDSId = hidID.Value).FirstOrDefault()
                If Not IsNothing(p3) Then
                    document.ReplaceText("<<S311>>", p3.S311)
                    document.ReplaceText("<<S321>>", p3.S321)
                    document.ReplaceText("<<S331>>", p3.S331)
                Else
                    document.ReplaceText("<<S311>>", "")
                    document.ReplaceText("<<S321>>", "")
                    document.ReplaceText("<<S331>>", "")
                End If

                '************************* End Section 3 *****************************

                '*************************  Section 4*****************************
                Dim p4 = (From a In data.MSDSSection04 Where a.MSDSId = hidID.Value And a.LanguageId = LanguageId).FirstOrDefault
                If Not IsNothing(p4) Then
                    document.ReplaceText("<<S411>>", p4.S411)
                    document.ReplaceText("<<S421>>", p4.S421)
                    document.ReplaceText("<<S431>>", p4.S431)
                    document.ReplaceText("<<S441>>", p4.S441)
                    document.ReplaceText("<<S451>>", p4.S451)
                Else
                    document.ReplaceText("<<S411>>", "") '
                    document.ReplaceText("<<S421>>", "") 'p4.S421)
                    document.ReplaceText("<<S431>>", "") ' p4.S431)
                    document.ReplaceText("<<S441>>", "") 'p4.S441)
                    document.ReplaceText("<<S451>>", "") ' p4.S451)
                End If


                '************************* End Section 4 *****************************
                '*************************  Section 5 *****************************
                Dim p5 = (From q In data.MSDSSection05 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p5) Then
                    document.ReplaceText("<<S511>>", p5.S511)
                    document.ReplaceText("<<S521>>", p5.S521)
                    document.ReplaceText("<<S531>>", p5.S531)
                    document.ReplaceText("<<S541>>", p5.S541)
                    document.ReplaceText("<<S551>>", p5.S551)
                    document.ReplaceText("<<S561>>", p5.S561)
                Else
                    document.ReplaceText("<<S511>>", "") ' p5.S511)
                    document.ReplaceText("<<S521>>", "") 'p5.S521)
                    document.ReplaceText("<<S531>>", "") 'p5.S531)
                    document.ReplaceText("<<S541>>", "") 'p5.S541)
                    document.ReplaceText("<<S551>>", "") 'p5.S551)
                    document.ReplaceText("<<S561>>", "") 'p5.S561)
                End If

                '************************* End Section 5 *****************************

                '*************************  Section 6 *****************************
                Dim p6 = (From q In data.MSDSSection06 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p6) Then
                    document.ReplaceText("<<S611>>", p6.S611)
                    document.ReplaceText("<<S621>>", p6.S621)
                    document.ReplaceText("<<S631>>", p6.S631)
                Else
                    document.ReplaceText("<<S611>>", "") ' p6.S611)
                    document.ReplaceText("<<S621>>", "") ' p6.S621)
                    document.ReplaceText("<<S631>>", "") ' p6.S621)
                End If

                '************************* End Section  6 *****************************

                '*************************  Section 7 *****************************
                Dim p7 = (From q In data.MSDSSection07 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p7) Then
                    document.ReplaceText("<<S711>>", p7.S711)
                    document.ReplaceText("<<S721>>", p7.S721)
                    document.ReplaceText("<<S731>>", p7.S731)
                    document.ReplaceText("<<S741>>", p7.S741)
                Else
                    document.ReplaceText("<<S711>>", "") ' p7.S711)
                    document.ReplaceText("<<S721>>", "") ' p7.S721)
                    document.ReplaceText("<<S731>>", "") ' p7.S721)
                    document.ReplaceText("<<S741>>", "") ' p7.S721)

                End If
                '************************* End Section  7 *****************************

                '*************************  Section 8 *****************************
                Dim p8 = (From q In data.MSDSSection08 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p8) Then
                    document.ReplaceText("<<S811>>", p8.S811)
                    document.ReplaceText("<<S821>>", p8.S821.Replace("#", Environment.NewLine))
                    document.ReplaceText("<<S831>>", p8.S831)
                    document.ReplaceText("<<S841>>", p8.S841)
                Else
                    document.ReplaceText("<<S811>>", "") ' p8.S811)
                    document.ReplaceText("<<S821>>", "") ' p8.S821)
                    document.ReplaceText("<<S831>>", "") 'p8.S831)
                    document.ReplaceText("<<S841>>", "") 'p8.S841)
                End If
                '************************* End Section 8 *****************************

                '*************************  Section 9 *****************************
                Dim p9 = (From a In data.MSDSSection09 Where a.MSDSId = hidID.Value And a.LanguageId = LanguageId).FirstOrDefault
                If Not IsNothing(p9) Then
                    document.ReplaceText("<<S911>>", p9.S911)
                    document.ReplaceText("<<S991>>", p9.S991)

                    document.ReplaceText("<<S921>>", p9.S921)
                    document.ReplaceText("<<S9101>>", p9.S9101)

                    document.ReplaceText("<<S931>>", p9.S931)
                    document.ReplaceText("<<S9111>>", p9.S9111)

                    document.ReplaceText("<<S941>>", p9.S941)
                    document.ReplaceText("<<S9121>>", p9.S9121)

                    document.ReplaceText("<<S951>>", p9.S951)
                    document.ReplaceText("<<S9131>>", p9.S9131)

                    document.ReplaceText("<<S961>>", p9.S961)
                    document.ReplaceText("<<S9141>>", p9.S9141)

                    document.ReplaceText("<<S971>>", p9.S971)
                    document.ReplaceText("<<S9151>>", p9.S9151)

                    document.ReplaceText("<<S981>>", p9.S981)
                    document.ReplaceText("<<S9161>>", p9.S9161)

                Else
                    document.ReplaceText("<<S911>>", "") '
                    document.ReplaceText("<<S991>>", "") 'p9.S991)

                    document.ReplaceText("<<S921>>", "") 'p9.S921)
                    document.ReplaceText("<<S9101>>", "") 'p9.S9101)

                    document.ReplaceText("<<S931>>", "") ' p9.S931)
                    document.ReplaceText("<<S9111>>", "") 'p9.S9111)

                    document.ReplaceText("<<S941>>", "") ' p9.S941)
                    document.ReplaceText("<<S9121>>", "") 'p9.S9121)

                    document.ReplaceText("<<S951>>", "") 'p9.S951)
                    document.ReplaceText("<<S9131>>", "") 'p9.S9131)

                    document.ReplaceText("<<S961>>", "") 'p9.S961)
                    document.ReplaceText("<<S9141>>", "") ' p9.S9141)

                    document.ReplaceText("<<S971>>", "") ' p9.S971)
                    document.ReplaceText("<<S9151>>", "") ' p9.S9151)

                    document.ReplaceText("<<S981>>", "") ' p9.S981)
                    document.ReplaceText("<<S9161>>", "") ' p9.S9161)

                End If

                '************************* End Section 9 *****************************

                '*************************  Section 10 *****************************
                Dim p10 = (From q In data.MSDSSection10 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p10) Then
                    document.ReplaceText("<<S1011>>", p10.S1011)
                    document.ReplaceText("<<S1021>>", p10.S1021)
                Else
                    document.ReplaceText("<<S1011>>", "")
                    document.ReplaceText("<<S1021>>", "")
                End If

                ''************************* End Section 10 *****************************


                '*************************  Section 13*****************************
                Dim p13 = (From q In data.MSDSSection13 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p13) Then
                    document.ReplaceText("<<S1311>>", p13.S1311)
                    document.ReplaceText("<<S1321>>", p13.S1321)
                    document.ReplaceText("<<S1331>>", p13.S1331)
                    document.ReplaceText("<<S1341>>", p13.S1341)
                Else
                    document.ReplaceText("<<S1311>>", "") '
                    document.ReplaceText("<<S1321>>", "") 'p13.S1321)
                    document.ReplaceText("<<S1331>>", "") 'p13.S1331)
                    document.ReplaceText("<<S1341>>", "") 'p13.S1341)

                End If
                '************************* End Section 13 *****************************

                '*************************  Section 14 ********************************
                Dim p14 = (From a In data.MSDSSection14 Where a.MSDSId = hidID.Value And a.LanguageId = LanguageId).FirstOrDefault
                If Not IsNothing(p14) Then
                    document.ReplaceText("<<S1411>>", p14.S1411)
                    document.ReplaceText("<<S1412>>", p14.S1412)
                    document.ReplaceText("<<S1413>>", p14.S1413)
                    document.ReplaceText("<<S1414>>", p14.S1414)

                    document.ReplaceText("<<S1421>>", p14.S1421)
                    document.ReplaceText("<<S1422>>", p14.S1422)
                    document.ReplaceText("<<S1423>>", p14.S1423)
                    document.ReplaceText("<<S1424>>", p14.S1424)

                    document.ReplaceText("<<S1431>>", p14.S1431)
                    document.ReplaceText("<<S1432>>", p14.S1432)
                    document.ReplaceText("<<S1433>>", p14.S1433)
                    document.ReplaceText("<<S1434>>", p14.S1434)

                    document.ReplaceText("<<S1415>>", p14.S1415)
                    document.ReplaceText("<<S1416>>", p14.S1416)

                    document.ReplaceText("<<S1425>>", p14.S1425)
                    document.ReplaceText("<<S1426>>", p14.S1426)
                    document.ReplaceText("<<S1435>>", p14.S1435)
                    document.ReplaceText("<<S1436>>", p14.S1436)
                    document.ReplaceText("<<S1441>>", p14.S1441)

                Else
                    document.ReplaceText("<<S1411>>", "") '
                    document.ReplaceText("<<S1412>>", "") ' p14.S1412)
                    document.ReplaceText("<<S1413>>", "") ' p14.S1413)
                    document.ReplaceText("<<S1414>>", "") ' p14.S1414)

                    document.ReplaceText("<<S1421>>", "") ' p14.S1421)
                    document.ReplaceText("<<S1422>>", "") ' p14.S1422)
                    document.ReplaceText("<<S1423>>", "") ' p14.S1423)
                    document.ReplaceText("<<S1424>>", "") ' p14.S1424)

                    document.ReplaceText("<<S1431>>", "") ' p14.S1431)
                    document.ReplaceText("<<S1432>>", "") ' p14.S1432)
                    document.ReplaceText("<<S1433>>", "") ' p14.S1433)
                    document.ReplaceText("<<S1434>>", "") ' p14.S1434)

                    document.ReplaceText("<<S1415>>", "") ' p14.S1415)
                    document.ReplaceText("<<S1416>>", "") ' p14.S1416)

                    document.ReplaceText("<<S1425>>", "") ' p14.S1425)
                    document.ReplaceText("<<S1426>>", "") ' p14.S1426)
                    document.ReplaceText("<<S1435>>", "") ' p14.S1435)
                    document.ReplaceText("<<S1436>>", "") ' p14.S1436)
                    document.ReplaceText("<<S1441>>", "")
                End If
                '************************* End  Section 14 *****************************

                '*************************  Section 15 *********************************
                Dim p15 = (From q In data.MSDSSection15 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p15) Then
                    document.ReplaceText("<<S1511>>", p15.S1511)
                    document.ReplaceText("<<S1521>>", p15.S1521)
                Else
                    document.ReplaceText("<<S1511>>", "")
                    document.ReplaceText("<<S1521>>", "")
                End If

                '************************* End Section 15 *****************************

                '*************************  Section 16 ********************************
                Dim p16 = (From q In data.MSDSSection16 Where q.MSDSId = hidID.Value And q.LanguageId = LanguageId).FirstOrDefault()
                If Not IsNothing(p16) Then
                    document.ReplaceText("<<S1621>>", p16.S1621)
                    document.ReplaceText("<<S1631>>", p16.S1631)
                    document.ReplaceText("<<S1641>>", p16.S1641)
                    document.ReplaceText("<<S1661>>", p16.S1661)
                Else
                    document.ReplaceText("<<S1621>>", "")
                    document.ReplaceText("<<S1631>>", "")
                    document.ReplaceText("<<S1641>>", "")
                    document.ReplaceText("<<S1661>>", "")
                End If

                '************************* End Section 16 *****************************
                'Xuat BBTT ra file word
                FileName = "MSDS__" & Now.ToFileTime & ".docx"
                ' Request.Url
                Dim URL As String = "viewerTemp/" & FileName
                If Not Directory.Exists(Server.MapPath("~/viewerTemp").ToString) Then
                    Directory.CreateDirectory(Server.MapPath("~/viewerTemp").ToString)
                End If
                document.SaveAs(Server.MapPath("~/viewerTemp").ToString & "\" & FileName)
                'xu ly convert file into pdf


                Dim strDocFile As String = FileName.Replace(".docx", ".doc")
                Dim strPDFFile As String = FileName.Replace(".docx", ".pdf")
                Dim strPNPFile As String = FileName.Replace(".docx", ".pnp")
                Dim applicationPath = Server.MapPath("~")
                If Not File.Exists(strDocFile) Then
                    Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
                    If (File.Exists(licenseFile)) Then
                        Dim license As Aspose.Words.License = New Aspose.Words.License()
                        license.SetLicense(licenseFile)
                        Dim doc As Aspose.Words.Document = New Aspose.Words.Document(Server.MapPath("~/viewerTemp").ToString & "\" & FileName)
                        strDocFile = Server.MapPath("~/viewerTemp").ToString & "\" & strDocFile
                        strPDFFile = Server.MapPath("~/viewerTemp").ToString & "\" & strPDFFile

                        doc.Save(strDocFile, SaveFormat.Doc)



                        'Dim swfFile As String = GetFileNameWithoutExtension(strDocFile) & ".swf"
                        'Dim pngTemp As String = Server.MapPath("~/viewerTemp").ToString & "\" & swfFile
                        'doc.Save(pngTemp, Aspose.Words.SaveFormat.Swf)



                        'If File.Exists(pngTemp) Then
                        '    Call writeSwf("../../viewerTemp/" & swfFile)
                        'End If




                        Dim builder As DocumentBuilder = New DocumentBuilder(doc)
                        'section 01 for merged field
                        If Not p1 Is Nothing Then
                            'nha cung cap
                            builder.MoveToMergeField("TenNhaCungCap")
                            builder.Write(p1.S301.ToString)
                            builder.MoveToMergeField("DiaChiNCC")
                            builder.Write(p1.S303.ToString)
                            builder.MoveToMergeField("DienThoaiNCC")
                            builder.Write(p1.S305.ToString)

                            'nha san xuat
                            builder.MoveToMergeField("NhaSanXuat")
                            builder.Write(p1.S201.ToString)


                            builder.MoveToMergeField("DiaChiNhaSanXuat")
                            builder.Write(p1.S203.ToString)

                            'nha san xuat footer
                            builder.MoveToMergeField("TenNhaSanXuat")
                            builder.Write(p1.S201.ToString)

                            'nha san xuat footer trang 1
                            builder.MoveToMergeField("TenNhaSanXuatTrang1")
                            builder.Write(p1.S201.ToString)

                        End If
                        '*************************  Section 2 *****************************
                        Dim p2detail = (From q In data.Section02Detail Where q.Section02Id = hidID.Value And q.LanguageID = LanguageId).ToList()
                        If p2detail.Count > 0 Then

                            Dim strHMLBeginTable_2 As String = "<table border='0' cellspacing='0' cellpadding='0' style='width:102%;border-collapse:collapse;'>"
                            strHMLBeginTable_2 = strHMLBeginTable_2 & "<tr><td colspan='4'  style='width:100.0%;border-top:solid windowtext 2.25pt;   border-left:none;border-bottom:solid windowtext 2.25pt;border-right:none;   background:#CCCCCC;padding:0mm 5.4pt 0mm 5.4pt'><h3 align='center' style='text-align:center'><span style='font-family:Times New Roman'>PHẦN II. THÔNG TIN VỀ THÀNH PHẦN NGUY HIỂM</span></h3></td></tr>"
                            strHMLBeginTable_2 = strHMLBeginTable_2 & "<tr style='mso-yfti-irow:1;page-break-inside:avoid'>   <td width='25%' style='width:38.32%;border-top:none;border-left:solid windowtext 1.0pt;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-bottom-alt:solid windowtext 2.25pt;   mso-border-right-alt:solid windowtext .5pt;padding:0mm 5.4pt 0mm 5.4pt'>   <h4 align='center' style='margin:0mm;margin-bottom:.0001pt;text-align:center'><span style='font-size:12.0pt'>Tên thành phần nguy hiểm</span></h4>   </td>   <td width='25%' style='width:16.14%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <h4 align='center' style='margin-top:0mm;margin-right:0mm;margin-bottom:0mm;   margin-left:-5.8pt;margin-bottom:.0001pt;text-align:center'><span style='font-size:12.0pt'>Số CAS</span></h4>   </td>   <td width='25%' style='width:24.16%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <p  align='center' style='text-align:center'><b>Công thức   hóa học</b></p>   </td>   <td width='25%' style='width:21.38%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <p  align='center' style='text-align:center'><b>Hàm lượng(% theo trọng lượng</b>)</p>   </td>  </tr>"
                            Dim strHTMLEndTable_2 As String = "</table>"

                            Dim strHTML_2 As String = ""
                            For i As Integer = 0 To p2detail.Count - 1
                                strHTML_2 = strHTML_2 & "<tr><td align='left' valign='middle' align='left' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p2detail(i).ThanhPhanNguyHiem & "</span></td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p2detail(i).SoCAS & "</span></td>" & _
                                                            "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p2detail(i).CongThucHoaHoc & "</span></td><td align='center' valign='middle' style='border:solid 1px #000'><span style='font-size:10pt;'>" & p2detail(i).HamLuong & "</span></td></tr>"
                            Next
                            builder.MoveToMergeField("Section2")
                            builder.InsertHtml(strHMLBeginTable_2 & strHTML_2 & strHTMLEndTable_2)
                            doc.Save(strDocFile, Aspose.Words.SaveFormat.Doc)
                        Else
                            Dim strHMLBeginTable_2 As String = "<table border='0' cellspacing='0' cellpadding='0' style='width:102%;border-collapse:collapse;'>"
                            strHMLBeginTable_2 = strHMLBeginTable_2 & "<tr><td colspan='4'  style='width:100.0%;border-top:solid windowtext 2.25pt;   border-left:none;border-bottom:solid windowtext 2.25pt;border-right:none;   background:#CCCCCC;padding:0mm 5.4pt 0mm 5.4pt'><h3 align='center' style='text-align:center'><span style='font-family:Times New Roman'>PHẦN II. THÔNG TIN VỀ THÀNH PHẦN NGUY HIỂM</span></h3></td></tr>"
                            strHMLBeginTable_2 = strHMLBeginTable_2 & "<tr style='mso-yfti-irow:1;page-break-inside:avoid'>   <td width='25%' style='width:38.32%;border-top:none;border-left:solid windowtext 1.0pt;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-bottom-alt:solid windowtext 2.25pt;   mso-border-right-alt:solid windowtext .5pt;padding:0mm 5.4pt 0mm 5.4pt'>   <h4 align='center' style='margin:0mm;margin-bottom:.0001pt;text-align:center'><span style='font-size:12.0pt'>Tên thành phần nguy hiểm</span></h4>   </td>   <td width='25%' style='width:16.14%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <h4 align='center' style='margin-top:0mm;margin-right:0mm;margin-bottom:0mm;   margin-left:-5.8pt;margin-bottom:.0001pt;text-align:center'><span style='font-size:12.0pt'>Số CAS</span></h4>   </td>   <td width='25%' style='width:24.16%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <p  align='center' style='text-align:center'><b>Công thức   hóa học</b></p>   </td>   <td width='25%' style='width:21.38%;border-top:none;border-left:none;   border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;   mso-border-left-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;   mso-border-bottom-alt:solid windowtext 2.25pt;mso-border-right-alt:solid windowtext .5pt;   padding:0mm 5.4pt 0mm 5.4pt'>   <p  align='center' style='text-align:center'><b>Hàm lượng(% theo trọng lượng</b>)</p>   </td>  </tr>"
                            Dim strHTMLEndTable_2 As String = "</table>"
                            Dim strHTML_2 As String = "<tr><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td>" & _
                                                            "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td style='width:22%; border:solid 1px #000'>&nbsp;</td></tr>"
                            builder.MoveToMergeField("Section2")
                            builder.InsertHtml(strHMLBeginTable_2 & strHTML_2 & strHTMLEndTable_2)
                            doc.Save(strDocFile, Aspose.Words.SaveFormat.Doc)
                        End If
                        '************************* End Section 2 *****************************


                        ''*************************  Section 11 *****************************
                        Dim p11 = (From a In data.MSDSSection11 Where a.MSDSId = hidID.Value And a.LanguageId = LanguageId).FirstOrDefault
                        Dim strHMLBeginTable As String = "<table border='0' cellspacing='0' cellpadding='0' style='width:102%;border-collapse:collapse;'>"
                        strHMLBeginTable = strHMLBeginTable & "<tr><td colspan='5'  style='width:100.0%;border-top:solid windowtext 2.25pt;   border-left:none;border-bottom:solid windowtext 2.25pt;border-right:none;   background:#CCCCCC;padding:0mm 5.4pt 0mm 5.4pt'><h3 align='center' style='text-align:center'><span style='font-family:Times New Roman'>PHẦN XI. THÔNG TIN VỀ ĐỘC TÍNH</span></h3></td></tr>"
                        strHMLBeginTable = strHMLBeginTable & "<tr style='mso-yfti-irow:1;height:16.15pt'>  <td width='23%' valign='top' style='width:23.06%;border-top:none;border-left:  solid windowtext 1.0pt;border-bottom:solid windowtext 2.25pt;border-right:  solid windowtext 1.0pt;mso-border-top-alt:solid windowtext 2.25pt;mso-border-top-alt:  2.25pt;mso-border-left-alt:.5pt;mso-border-bottom-alt:2.25pt;mso-border-right-alt:  .5pt;mso-border-color-alt:windowtext;mso-border-style-alt:solid;padding:0mm 5.4pt 0mm 5.4pt;  height:16.15pt'>  <h3 align='center' style='text-align:center'><span style='font-size:10.0pt;  font-family:Times New Roman,serif'>Tên thành phần</span></h3>  </td>  <td width='19%' valign='top' style='width:19.06%;border-top:none;border-left:  none;border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;  mso-border-top-alt:solid windowtext 2.25pt;mso-border-left-alt:solid windowtext .5pt;  mso-border-top-alt:2.25pt;mso-border-left-alt:.5pt;mso-border-bottom-alt:  2.25pt;mso-border-right-alt:.5pt;mso-border-color-alt:windowtext;mso-border-style-alt:  solid;padding:0mm 5.4pt 0mm 5.4pt;height:16.15pt'>  <h3 align='center' style='text-align:center'><span style='font-size:10.0pt;  font-family:Times New Roman,serif'>Loại ngưỡng </span></h3>  </td>  <td width='17%' valign='top' style='width:17.18%;border-top:none;border-left:  none;border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;  mso-border-top-alt:solid windowtext 2.25pt;mso-border-left-alt:solid windowtext .5pt;  mso-border-top-alt:2.25pt;mso-border-left-alt:.5pt;mso-border-bottom-alt:  2.25pt;mso-border-right-alt:.5pt;mso-border-color-alt:windowtext;mso-border-style-alt:  solid;padding:0mm 5.4pt 0mm 5.4pt;height:16.15pt'>  <h3 align='center' style='text-align:center'><span style='font-size:10.0pt;  font-family:Times New Roman,serif'>Kết quả</span></h3>  </td>  <td width='22%' valign='top' style='width:22.22%;border-top:none;border-left:  none;border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;  mso-border-top-alt:solid windowtext 2.25pt;mso-border-left-alt:solid windowtext .5pt;  mso-border-top-alt:2.25pt;mso-border-left-alt:.5pt;mso-border-bottom-alt:  2.25pt;mso-border-right-alt:.5pt;mso-border-color-alt:windowtext;mso-border-style-alt:  solid;padding:0mm 5.4pt 0mm 5.4pt;height:16.15pt'>  <h3 align='center' style='text-align:center'><span style='font-size:10.0pt;  font-family:Times New Roman,serif'>Đường tiếp xúc</span></h3>  </td>  <td width='18%' valign='top' style='width:18.5%;border-top:none;border-left:  none;border-bottom:solid windowtext 2.25pt;border-right:solid windowtext 1.0pt;  mso-border-top-alt:solid windowtext 2.25pt;mso-border-left-alt:solid windowtext .5pt;  mso-border-top-alt:2.25pt;mso-border-left-alt:.5pt;mso-border-bottom-alt:  2.25pt;mso-border-right-alt:.5pt;mso-border-color-alt:windowtext;mso-border-style-alt:  solid;padding:0mm 5.4pt 0mm 5.4pt;height:16.15pt'>  <h3 align='center' style='text-align:center'><span style='font-size:10.0pt;  font-family:Times New Roman,serif'>Sinh vật thử</span></h3>  </td> </tr>"
                        Dim strHTMLEndTable As String = "</table>"
                        Dim strHTML As String = ""
                        If Not IsNothing(p11) Then
                            '' Detail Section 111
                            Dim p11Detail = (From q In data.Section11Detail Where q.Section11Id = p11.Section11Id).ToList()
                            If p11Detail.Count > 0 Then
                                For i As Integer = 0 To p11Detail.Count - 1
                                    strHTML = strHTML & "<tr><td align='left' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p11Detail(i).TenThanhPhan & "</span></td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p11Detail(i).LoaiNguong & "</span></td>" & _
                                                            "<td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p11Detail(i).KetQua & "</span></td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p11Detail(i).DuongTiepXuc & "</span></td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p11Detail(i).SinhVatThu & "</span></td></tr>"
                                Next
                            Else
                                strHTML = strHTML & "<tr><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td>" & _
                                                        "<td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td></tr>"
                            End If
                            strHTML = strHTML & "<tr> <td colspan='5' style='width:20%; border:solid 1px #000'><div><span style='font-size:10pt;'><b>1. Các ảnh hưởng mãn tính với người: </b><br/>" & p11.S1141.ToString.Replace(Chr(10), "<br/>").Replace(Chr(34), "<br/>") & "</span></div>" & _
                                                    "<div><span style='font-size:10pt;'><b>2. Các ảnh hưởng độc khác: </b><br/>" & p11.S1151.ToString.Replace(Chr(10), "<br/>").Replace(Chr(34), "<br/>") & "</span></div></td></tr>"
                        Else
                            strHTML = strHTML & "<tr><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td>" & _
                                                                                             "<td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:20%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td></tr>"
                            strHTML = strHTML & "<tr> <td colspan='5' style='width:20%; border:solid 1px #000'><div><span style='font-size:10pt;'><b>1. Các ảnh hưởng mãn tính với người: </b></span></div>" & _
                                                 "<div><span style='font-size:10pt;'><b>2. Các ảnh hưởng độc khác: </b></span></div></td></tr>"
                        End If
                        builder.MoveToMergeField("Section11")
                        builder.InsertHtml(strHMLBeginTable & strHTML & strHTMLEndTable)
                        doc.Save(strDocFile, Aspose.Words.SaveFormat.Doc)

                        '************************* End Section 11 *****************************




                        '*************************  Section 12 *****************************
                        Dim p12 = (From a In data.MSDSSection12 Where a.MSDSId = hidID.Value And a.LanguageId = LanguageId).FirstOrDefault
                        strHMLBeginTable = "<table border='0' cellspacing='0' cellpadding='0' style='width:102%;border-collapse:collapse;'>"
                        strHMLBeginTable = strHMLBeginTable & "<tr><td colspan='4'  style='width:100.0%;border-top:solid windowtext 2.25pt;   border-left:none;border-bottom:solid windowtext 2.25pt;border-right:none;   background:#CCCCCC;padding:0mm 5.4pt 0mm 5.4pt'><h3 align='center' style='text-align:center'><span style='font-family:Times New Roman'>PHẦN XII. THÔNG TIN VỀ SINH THÁI MÔI TRƯỜNG</span></h3></td></tr>"
                        strHTMLEndTable = "</table>"
                        strHTML = ""
                        If Not IsNothing(p12) Then
                            strHTML = strHTML & "<tr> <td colspan='4' style='border:solid 1px #000'><div><span style='font-size:10pt;'><b>1. Độc tính với sinh vật: </b></span></div></td></tr>"
                            strHTML = strHTML & "<tr><td align='center' valign='middle' align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'> <b>Tên thành phần</b></span></td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'><b>Loại sinh vật</b></span></td>" & _
                                                               "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'><b>Chu kỳ ảnh hưởng</b></span></td><td align='center' valign='middle' style='border:solid 1px #000'><span style='font-size:10pt;'><b>Kết quả</b></span></td></tr>"

                            '' Detail Section 111
                            Dim p12Detail = (From q In data.Section12Detail Where q.Section12Id = p12.Section12Id).ToList()
                            If Not IsNothing(p12Detail) Then
                                For i As Integer = 0 To p12Detail.Count - 1
                                    strHTML = strHTML & "<tr><td align='left' valign='middle' align='left' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p12Detail(i).TenThanhPhan & "</span></td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p12Detail(i).LoaiSinhVat & "</span></td>" & _
                                                                "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>" & p12Detail(i).ChukyAnhHuong & "</span></td><td align='center' valign='middle' style='border:solid 1px #000'><span style='font-size:10pt;'>" & p12Detail(i).KetQua & "</span></td></tr>"
                                Next
                            Else
                                strHTML = strHTML & "<tr><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td>" & _
                                                          "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'>&nbsp;</td><td style='width:22%; border:solid 1px #000'>&nbsp;</td></tr>"
                            End If
                            strHTML = strHTML & "<tr> <td colspan='4' style='border:solid 1px #000'><div><span style='font-size:10pt;'><b>2. Tác động trong môi trường: </b></span></div>" & _
                                                        "<div><span style='font-size:10pt;'>" & p12.S1221.ToString.Replace(Chr(10), "<br/>").Replace(Chr(34), "<br/>") & "</span></div></td></tr>"
                        Else
                            strHTML = strHTML & "<tr> <td colspan='4' style='border:solid 1px #000'><div><span style='font-size:10pt;'><b>1. Độc tính với sinh vật: </b></span></div></td></tr>"
                            strHTML = strHTML & "<tr><td align='center' valign='middle' align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'> Tên thành phần</span></td><td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>Loại sinh vật</span></td>" & _
                                                                                           "<td align='center' valign='middle' style='width:25%; border:solid 1px #000; font-family:Times New Roman;'><span style='font-size:10pt;'>Chu kỳ ảnh hưởng</span></td><td align='center' valign='middle' style='border:solid 1px #000'><span style='font-size:10pt;'>Kết quả</span></td></tr>"

                            strHTML = strHTML & "<tr> <td colspan='4' style='border:solid 1px #000'><div><span style='font-size:10pt;'><b>2. Tác động trong môi trường: </b></span></div>" & _
                                               "<div><span style='font-size:10pt;'></span></div></td></tr>"
                        End If
                        '************************* End  Section 12 *****************************
                        builder.MoveToMergeField("Section12")
                        builder.InsertHtml(strHMLBeginTable & strHTML & strHTMLEndTable)

                        'Section 03 hinh do

                        'seciton 03

                        Dim section03 = (From q In data.uspSection03GetOtherList(hidID.Value)).ToList
                        'VatChat
                        Dim strVatChat As String = ""
                        Dim strSucKhoe As String = ""
                        Dim strMoiTruong As String = ""

                        For Each a In section03
                            If a.TypeId = 1 Then
                                strVatChat = strVatChat & "<br>- " & a.OtherListName & " - " & a.PhanLoai
                            ElseIf a.TypeId = 2 Then
                                strSucKhoe = strSucKhoe & "<br>- " & a.OtherListName & " - " & a.PhanLoai
                            Else
                                strMoiTruong = strMoiTruong & "<br>- " & a.OtherListName & " - " & a.PhanLoai
                            End If
                        Next

                        If strVatChat = "" Then
                            strVatChat = "Không được phân loại"
                        Else
                            strVatChat = strVatChat.Substring(4, strVatChat.Length - 4)
                        End If
                        If strSucKhoe = "" Then
                            strSucKhoe = "Không được phân loại"
                        Else
                            strSucKhoe = strSucKhoe.Substring(4, strSucKhoe.Length - 4)
                        End If
                        If strMoiTruong = "" Then
                            strMoiTruong = "Không được phân loại"
                        Else
                            strMoiTruong = strMoiTruong.Substring(4, strMoiTruong.Length - 4)
                        End If
                        'write in to template
                        builder.MoveToMergeField("VatChat")
                        builder.InsertHtml("<span style='font-size:12pt;'>" & strVatChat & "</span>")

                        builder.MoveToMergeField("SucKhoe")
                        builder.InsertHtml("<span style='font-size:12pt;'>" & strSucKhoe & "</span>")

                        builder.MoveToMergeField("MoiTruong")
                        builder.InsertHtml("<span style='font-size:12pt;'>" & strMoiTruong & "</span>")

                        'tu canh bao
                        Dim strTuCanhBao As String = ""

                        For Each a In section03
                            strTuCanhBao = strTuCanhBao & "@" & a.TuCanhBao.ToString
                        Next
                        builder.MoveToMergeField("LOICANHBAO")
                        builder.Write(getWarning(strTuCanhBao.ToUpper))

                        Dim hinhdoCanhBao = (From q In data.uspSection03GetHinhDo(hidID.Value) Where q.LoaiId = 1 Select q.FileURL).Distinct.ToList
                        Dim hinhdovanChuyen = (From q In data.uspSection03GetHinhDo(hidID.Value) Where q.LoaiId = 2 Select q.FileURL).Distinct.ToList
                        'hinh do canh bao
                        Dim _hinhdo As String = "IconWarning"
                        Dim j = 1
                        For Each a In hinhdoCanhBao
                            InsertImageFromURL(builder, a, 50, 50, _hinhdo & j.ToString)
                            j = j + 1
                        Next
                        If hinhdoCanhBao.Count < 1 Then
                            builder.MoveToMergeField("HinhDoCanhBao")
                            builder.InsertHtml("<br><span style='font-size:12pt;'>Không có hình đồ cảnh báo</span>")
                        Else
                            builder.MoveToMergeField("HinhDoCanhBao")
                            builder.Write("")
                        End If
                        'insert khoang trong cua hinh do
                        For j = 1 To 8
                            builder.MoveToMergeField(_hinhdo & j.ToString)
                            builder.Write("")
                        Next

                        'hinh do van chuyen
                        Dim _vanchuyen As String = "VanChuyen"
                        Dim k = 1
                        For Each a In hinhdovanChuyen
                            InsertImageFromURL(builder, a, 50, 50, _vanchuyen & k.ToString)
                            k = k + 1
                        Next
                        If hinhdoCanhBao.Count < 1 Then
                            builder.MoveToMergeField("HinhDoVanChuyen")
                            builder.InsertHtml("<br><span style='font-size:12pt;'>Không có hình đồ vận chuyển</span>")
                        Else
                            builder.MoveToMergeField("HinhDoVanChuyen")
                            builder.Write("")
                        End If
                        'insert khoang trong cua hinh do
                        For j = 1 To 8
                            builder.MoveToMergeField(_vanchuyen & j.ToString)
                            builder.Write("")
                        Next


                        'canh bao nguy co
                        Dim strCanhBaoNguyCo As String = ""
                        For Each a In section03
                            strCanhBaoNguyCo = strCanhBaoNguyCo & "<br>- " & a.CanhBaoNguyCo.ToString
                        Next
                        If strCanhBaoNguyCo = "" Then
                            strCanhBaoNguyCo = "Không có cảnh báo nguy cơ"
                        Else
                            strCanhBaoNguyCo = strCanhBaoNguyCo.Substring(4, strCanhBaoNguyCo.Length - 4)
                        End If
                        builder.MoveToMergeField("CanhBaoNguyCo")
                        builder.InsertHtml("<span style='font-size:12pt;'>" & strCanhBaoNguyCo & "</span>")

                        doc.Save(strDocFile, Aspose.Words.SaveFormat.Doc)
                        'save pdf
                        'doc = New Aspose.Words.Document(strDocFile)
                        'doc.Save(strPDFFile, SaveFormat.Pdf)
                        Dim swfFile As String = GetFileNameWithoutExtension(strDocFile) & ".swf"
                        Dim pngTemp As String = Server.MapPath("~/viewerTemp").ToString & "\" & swfFile
                        doc.Save(pngTemp, Aspose.Words.SaveFormat.Swf)

                        If File.Exists(pngTemp) Then
                            Call writeSwf("../../viewerTemp/" & swfFile)
                        End If

                        If Not IsNothing(doc) Then
                            doc = Nothing
                        End If



                    End If
                    ' Call exportFile(strPDFFile)
                End If
            End Using
        End Using
    End Sub
    Private Sub writeSwf(ByVal _swf As String)
        Try
            Dim _xmlFile As String = ""
            Dim _strInfo As String = ""
            If _swf.ToLower.EndsWith(".swf") Then
                _strInfo &= " writeSwf('" & _swf & "');" & vbCrLf
            End If
            Excute_Javascript(_strInfo, Me.Page, True)
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub btnPublish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPublish.Click
        Dim StringId As String = ""
        Dim intTotal As Integer
        Using data As New VSEntities
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    StringId += grdShow.DataKeys(item.RowIndex)("Id").ToString & ","
                    'Write Code here
                End If
            Next
            Response.Redirect("../../Page/MSDS/ActionList.aspx?Id=" & StringId & "&NStatusId=3")
        End Using
    End Sub


    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Dim strCol As String() = {"STT", "Item Code", "Item Name", "Vendor Code", "Vendor Name", "Created", "Expired", "Status"}
        Using data As New VSEntities

            Dim dtmCreatedFrom As DateTime = StringToDate(txtCreatedFrom.Text)
            Dim dtmCreatedTo As DateTime = StringToDate(IIf(String.IsNullOrEmpty(txtCreatedTo.Text.Trim) = True, "31/12/3999", txtCreatedTo.Text.Trim), "dd/mm/yyyy")
            Dim p = data.uspMsdsoriginalSelectAll(txtItemcode.Text _
            , txtItemname.Text _
            , txtVendorcode.Text _
            , txtVendorname.Text _
            , dtmCreatedFrom _
            , dtmCreatedTo, ddlStatusId.SelectedValue _
            , ddlFieldSort.SelectedValue, txtCAS.Text _
           , 1, 1000).ToList

            If ddlFieldSort.SelectedValue = "--- Chọn ---" Then
                p = (From a In data.uspMsdsoriginalSelectAll(txtItemcode.Text _
                    , txtItemname.Text _
                    , txtVendorcode.Text _
                    , txtVendorname.Text _
                    , dtmCreatedFrom _
                    , dtmCreatedTo, ddlStatusId.SelectedValue _
                    , ddlFieldSort.SelectedValue, txtCAS.Text _
                   , 1, 1000) Order By a.Created Descending Select a).ToList
            End If


            'Export to excel
            Response.ContentType = "application/csv"
            Response.Charset = ""
            Response.AddHeader("Content-Disposition", "attachment;filename=MSDS.xls")
            Response.ContentEncoding = Encoding.Unicode
            Response.BinaryWrite(Encoding.Unicode.GetPreamble())

            Dim sb As StringBuilder = New StringBuilder()

            For i As Integer = 0 To strCol.Length - 1
                sb.Append(strCol(i))
                If (i < strCol.Length - 1) Then
                    sb.Append(vbTab)
                End If
            Next

            Response.Write(sb.ToString() & vbCrLf)
            Response.Flush()
            For i As Integer = 0 To p.Count - 1
                sb = New StringBuilder()
                sb.Append((i + 1).ToString())
                sb.Append(vbTab)
                sb.Append(p(i).ItemCode)
                sb.Append(vbTab)
                sb.Append((p(i).ItemName))
                sb.Append(vbTab)
                sb.Append(p(i).VendorCode)
                sb.Append(vbTab)
                sb.Append(p(i).Vendorname)
                sb.Append(vbTab)
                sb.Append(CType(p(i).Created, DateTime).ToString("dd/MM/yyyy"))
                sb.Append(vbTab)

                ' sb.Append(p(i).Expired)


                Using _data As New VSEntities
                    Dim _MSDSId As Integer = p(i).Id
                    Dim _section16 = (From q In _data.MSDSSection16 Where q.MSDSId = _MSDSId Select q).FirstOrDefault
                    If Not _section16 Is Nothing Then
                        If Not _section16.S1651 Is Nothing Then
                            sb.Append(_section16.S1651)
                        End If
                    End If
                End Using

                sb.Append(vbTab)
                sb.Append(p(i).StatusName)
                Response.Write(sb.ToString() & vbCrLf)
                Response.Flush()
            Next
            Response.End()
        End Using

    End Sub
    Function getWarning(ByVal str As String) As String
        Dim lstArr = str.Split("@")
        If lstArr.Contains("NGUY HIỂM") Then
            Return "NGUY HIỂM"
        ElseIf lstArr.Contains("CẢNH BÁO") Then
            Return "CẢNH BÁO"
        Else
            Return "KHÔNG CÓ"
        End If

    End Function

    Private Sub InsertImageFromURL(ByVal builder As DocumentBuilder, ByVal url As String, ByVal width As Double, ByVal height As Double, ByVal fieldName As String)


        Try
            'Prepare the web page we will be asking for
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
            request.Method = "GET"
            request.ContentType = "image/JPEG"
            request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0"
            'Execute the request
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            'We will read data via the response stream
            Dim resStream As Stream = response.GetResponseStream()
            'Write content into the MemoryStream
            Dim resReader As New BinaryReader(resStream)
            Dim imgStream As New MemoryStream(resReader.ReadBytes(CInt(response.ContentLength)))
            'Insert image into the document
            builder.MoveToMergeField(fieldName)
            builder.InsertImage(imgStream, width, height)
            'Handle web exceptions
        Catch ex As Exception

        End Try



    End Sub
End Class
